package controllers;

import helpers.HeaderHelper;

import java.io.IOException;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import models.Domain;

public class WhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		//Set Header website
		HeaderHelper headerHelper = new HeaderHelper();
		
		//Init cache
		Cache cache=null;
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String domainName = path.toLowerCase().replaceAll("/w/", "");
		
		//Set cache
		String cachename = "whois_" + domainName;
		Domain domain = new Domain();
		if (cache.containsKey(cachename)) {
        	domain = (Domain) cache.get(cachename);
        	System.out.println("List Domain: cache print");
        } else {
			try {
				ObjectifyService.register(Domain.class);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			Objectify ofy = ObjectifyService.begin();
			try {
				domain = ofy.get(new Key<Domain>(Domain.class, domainName));
				//domain = ofy.query(Domain.class).filter("name", domainName).get();
			} catch (Exception e) {
				domain = null;
			}
			
			if (domain == null) {
				domain = new Domain();
				domain.setName(domainName);
			} else {
				cache.put(cachename, domain);
				System.out.println("List Domain: data print");
			}
        }
		//Set info header
		headerHelper.setTitle(domainName + " - Whois info");
		headerHelper.setOgtitle(domainName + " - Whois info");
		
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("domain", domain);
		try {
			request.getRequestDispatcher("/pages/whois.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
